import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Button, Card, Input, Table, Divider, Form, Select, Row, Col, Badge, Tag, Popconfirm, message } from 'antd';
import { debug } from 'util';
import moment from 'moment';
import styles from './Menu.less';
import request from '@/utils/request';
import { stringify } from 'qs';
import router from 'umi/router';
import { getFormData } from '@/utils/Yvan';

const FormItem = Form.Item;
const Option = Select.Option;

@connect(({ PagesModel }) => (
  { PagesModel }
))
@Form.create()
export default class Sys extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      queryForm: {},
      pageInfo: {
        pageSize: 10,
        current: 1,
      },
      dataSource: [],
      loading: false,
      loading_button: false
    };
    const { PagesModel, location: { pathname } } = props;
    if (pathname in PagesModel) {
      const { queryForm, pageInfo } = PagesModel[pathname];
      this.state.queryForm = queryForm;
      this.state.pageInfo = pageInfo;
    }
  }

  componentDidMount() {
    this.refreshTable();
  }

  refreshTable = (opts) => {
    const { dispatch } = this.props;

    const paramTarget = {
      ...this.state,
      loading: true,
      ...opts,
    };
    this.setState({
      loading: true,
      ...opts,
    });

    const params = {
      page: paramTarget.pageInfo.current,
      rows: paramTarget.pageInfo.pageSize,
      ...paramTarget.queryForm,
    }

    request('/api/sys/system/query', {
      method: 'POST',
      body: getFormData(params)

    }).then((root) => {
      this.setState({
        dataSource: root.data,
        pageInfo: {
          total: parseInt(root.pagination.count),
          pageSize: root.pagination.pageSize,
          current: root.pagination.pageNo,
        },
        loading: false,
        loading_button: false,
      })

      //保存当前状态
      const { PagesModel, location: { pathname } } = this.props;
      const { queryForm, pageInfo } = paramTarget;
      PagesModel[pathname] = { queryForm, pageInfo }
    })
  }

  handleTableChange = (pagination, filters, sorter) => {
    const { queryForm } = this.state;
    const { status } = filters;
    if (status) {
      queryForm.status = status.join(',');
    }

    this.refreshTable({
      queryForm: { ...queryForm },
      pageInfo: {
        current: pagination.current,
        pageSize: pagination.pageSize,
      }
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.refreshTable({
      queryForm: {},
      pageInfo: {
        ...this.state.pageInfo,
        current: 1
      }
    });
  };

  handleSearch = e => {
    e.preventDefault();
    const {  form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      this.refreshTable({
        queryForm: fieldsValue,
        pageInfo: {
          ...this.state.pageInfo,
          current: 1
        },
        loading_button: true
      });
    });
  }

  handleAdd = () => {
    router.push({
      pathname: '/admin/system/sys/dialog',
      query: {
        isEdit: false,
        sysId: ''
      }
    });
  }

  handleEdit = (record) => {
    router.push({
      pathname: '/admin/system/sys/dialog',
      query: {
        isEdit: true,
        sysId: record.sysId
      }
    });
  }

  handleEnable = (record, actived) => {
    this.setState({ loading: true });
    const formData = new FormData();
    formData.append('sysId', record.sysId);
    formData.append('status', actived);

    request(`/api/sys/system/updateSystemStatus`, {
      method: 'POST',
      body: formData
    }).then((root) => {
      if (root.success) {
        message.success('操作成功');
        this.refreshTable({});
        return;
      }
      message.error(root.msg);
      this.setState({ loading: false });
    })
  }

  renderForm = () => {
    const { getFieldDecorator } = this.props.form;
    const { loading_button, queryForm: { status } } = this.state;

    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="检索条件">
              {getFieldDecorator('queryProperties')(<Input placeholder="平台编码/名称/说明" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="启用状态">
              {
                getFieldDecorator('status', {
                  initialValue: status,
                })(
                  <Select placeholder="请选择" style={{ width: '100%' }} >
                    <Option value="">全部</Option>
                    <Option value="1">启用中</Option>
                    <Option value="-1">已停用</Option>
                  </Select>
                )
              }
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" loading={loading_button}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {
    const { pageInfo, dataSource, loading, queryForm: { status } } = this.state;

    return (
      <Card>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
          <div className={styles.tableListOperator}>
            <Button icon="plus" type="primary" onClick={() => this.handleAdd()}>新建</Button>
          </div>
          <Table bordered
            size="small"
            scroll={{ x: 480 }}
            columns={[
              {
                title: '操作', key: 'action', width: 120, fixed: 'left', render: (text, record) => {
                  const action = [];
                  action.push(<Tag key="edit1" color="#108ee9" onClick={() => this.handleEdit(record)}>修改</Tag>);


                  if (record.status === '1') {

                    action.push(
                      <Popconfirm key="edit2" placement="topLeft" title="确认禁用？" onConfirm={() => this.handleEnable(record, "-1")} okText="禁用" cancelText="取消">
                        <Tag color="red">禁用</Tag>
                      </Popconfirm>
                    );
                  } else {
                    action.push(
                      <Popconfirm key="edit2" placement="topLeft" title="确认启用？" onConfirm={() => this.handleEnable(record, "1")} okText="启用" cancelText="取消">
                        <Tag color="green">启用</Tag>
                      </Popconfirm>
                    );
                  }
                  return (
                    <Fragment>
                      {action}
                    </Fragment>
                  )
                }
              },
              { title: '平台编码', dataIndex: 'sysCode', width: 100 },
              { title: '平台名称', dataIndex: 'sysName' },
              { title: '平台url', dataIndex: 'sysUrl' },
              { title: '说明', dataIndex: 'sysDesp' },
              {
                title: '启用状态', dataIndex: 'status', width: 100,
                filterMultiple: false,
                filtered: (status != null && status != ''),
                filteredValue: ((status != null && status != '') ? [status] : null),
                filters: [
                  { value: "1", text: '启用' },
                  { value: "-1", text: '停用' },
                ],
                render(val) {
                  if (val === "1") {
                    return <Badge status="success" text="启用中" />;
                  }
                  return <Badge status="error" text="已停用" />;
                },
              },
              { title: '更新时间', dataIndex: 'timeUpdate', width: 150, sorter: true, render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span> },
            ]}
            pagination={{
              size: "small",
              showSizeChanger: true,
              showQuickJumper: false,
              showTotal: (total, range) => `${range[0]}-${range[1]} / ${total} 记录`,
              ...pageInfo
            }}
            loading={loading}
            dataSource={dataSource}
            onChange={this.handleTableChange}
            rowKey="sysId" />
        </div>
      </Card>
    );
  }
}

